/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.questionnaire.question;

import com.blandware.atleap.common.QuestionnaireModuleConstants;
import com.blandware.atleap.model.questionnaire.Question;
import com.blandware.atleap.model.questionnaire.Questionnaire;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.questionnaire.QuestionnaireManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.questionnaire.QuestionForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.MergeUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.questionnaire.QuestionnaireModuleWebConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.orm.ObjectOptimisticLockingFailureException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>Updates question.</p>
 * <p><a href="UpdateQuestionAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.4 $ $Date: 2008/04/29 17:51:54 $
 * @struts.action path="/questionnaire/question/update"
 * name="questionForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="questionnaire-question-update"
 * @struts.action-forward name="inputForward"
 * path=".questionnaire.question.update"
 * @struts.action-forward name="listQuestions"
 * path="/questionnaire/question/list.do"
 * redirect="true"
 * @struts.action-forward name="listQuestionnaires"
 * path="/questionnaire/questionnaire/list.do"
 * redirect="true"
 * @struts.action-forward name="callUpdateQuestion"
 * path="/questionnaire/question/callUpdate.do"
 * redirect="false"
 */
public final class UpdateQuestionAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();
        QuestionForm questionForm = (QuestionForm) form;
        String localesMode = questionForm.getLocalesMode();

        request.setAttribute("validationRegexes", QuestionnaireModuleWebConstants.VALIDATION_REGEXES);

		if ( isBackPressed(request) ) {
            // First check, may be session has been invalidated and we need to
            // fill content locales again
            if (session.getAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY) == null) {
                List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
                session.setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);
            }

            // check 'check all' ckeckbox if needed
            questionForm.setAllCheckedFlagForTitleCheckboxes(request, localesMode);

			return mapping.findForward("inputForward");
		}

		if ( isCancelled(request) ) {
            if ( session.getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
                String redirectUrl = (String) session.getAttribute(WebappConstants.REDIRECT_URL_KEY);
                ActionForward redirect = new ActionForward(redirectUrl, true);
                return redirect;
            }
			return mapping.findForward("listQuestions");
		}

		if ( session.getAttribute(QuestionnaireModuleWebConstants.QUESTION_SUBMITTED_ACTION_KEY) != null ) {
			return mapping.findForward("listQuestions");
		}
		session.setAttribute(QuestionnaireModuleWebConstants.QUESTION_SUBMITTED_ACTION_KEY, "update");

        Long questionnaireId = null;
        if (!GenericValidator.isBlankOrNull(questionForm.getQuestionnaireId())) {
            questionnaireId = Long.valueOf(questionForm.getQuestionnaireId());
        } else {
            questionnaireId = (Long) session.getAttribute(QuestionnaireModuleWebConstants.QUESTIONNAIRE_ID_KEY);
        }
        if (questionnaireId == null) {
            if (log.isWarnEnabled()) {
                log.warn("Missing questionnaire ID. Returning to index...");
            }
            return mapping.findForward("listQuestionnaires");
        }

		Long questionId = null;
		if ( !GenericValidator.isBlankOrNull(questionForm.getId()) ) {
			questionId = Long.valueOf(questionForm.getId());
		} else {
			if ( log.isWarnEnabled() ) {
				log.warn("Missing question ID. Returning to list...");
			}
			return mapping.findForward("listQuestions");
		}

		session.setAttribute(QuestionnaireModuleWebConstants.QUESTION_ID_KEY, questionId);

		QuestionnaireManager questionnaireManager = (QuestionnaireManager) getBean(QuestionnaireModuleConstants.QUESTIONNAIRE_MANAGER_BEAN);
        Questionnaire questionnaire = questionnaireManager.retrieveQuestionnaire(questionnaireId);
		if ( questionnaire == null ) {
			// questionnaire not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("ownerNotFound", new ActionMessage("questionnaire.question.errors.ownerNotFound"));
			saveErrors(request, errors);
			return mapping.findForward("listQuestionnaires");
		}

        if (questionnaire.getFixed().booleanValue()) {
			// questionnaire is fixed, it cannot be edited
			ActionMessages errors = new ActionMessages();
			errors.add("questionnaireIsFixed", new ActionMessage("questionnaire.questionnaire.errors.fixed"));
			saveErrors(request, errors);
			return mapping.findForward("listQuestions");
        }

		Question question = questionnaireManager.retrieveQuestion(questionId);

		if ( question == null ) {
			// question not found. it might be deleted by someone else
			ActionMessages errors = new ActionMessages();
			errors.add("questionNotFound", new ActionMessage("questionnaire.question.errors.notFound"));
			saveErrors(request, errors);
			return mapping.findForward("listQuestions");
		}

		Map newTitle = question.getTitle();

		WebappUtil.copyProperties(question, questionForm, request);

        if (!"current".equalsIgnoreCase(localesMode) && !"all".equalsIgnoreCase(localesMode)) {
            localesMode = "selected";
        }

        Map titleMap = questionForm.getTitleMap();
        Map titleCheckedBoxes = questionForm.getTitleCheckedBoxes();
        if ("selected".equalsIgnoreCase(localesMode)) {
            for (Iterator i = titleMap.entrySet().iterator(); i.hasNext();) {
                Map.Entry entry = (Map.Entry) i.next();
                String localeIdentifier = (String) entry.getKey();
                if (titleCheckedBoxes.get(localeIdentifier) == null) {
                    // if this locale is not checked, replace annotation with old one
                    titleMap.put(localeIdentifier, newTitle.get(localeIdentifier));
                }
            }
        }

		question.setTitle(titleMap);

		try {
			questionnaireManager.updateQuestion(question, questionnaireId);
		} catch ( BeanAlreadyExistsException e ) {
			// question already exists

            // check 'check all' ckeckbox if needed
            questionForm.setAllCheckedFlagForTitleCheckboxes(request, localesMode);

			ActionMessages errors = new ActionMessages();
			errors.add("questionAlreadyExists", new ActionMessage("questionnaire.question.errors.alreadyExists"));
			saveErrors(request, errors);
			return mapping.getInputForward();
		} catch ( ObjectOptimisticLockingFailureException e ) {
			// question item was updated or deleted by another transaction
			ActionMessages errors = new ActionMessages();
			errors.add("updateFailed", new ActionMessage("questionnaire.question.errors.updateFailed"));
			saveErrors(request, errors);

			// merge title
			Map oldTitle = titleMap;
			Map mergedTitle = new HashMap();
			for ( Iterator i = oldTitle.entrySet().iterator(); i.hasNext(); ) {
				Map.Entry entry = (Map.Entry) i.next();
				String locale = (String) entry.getKey();
				String oldValue = (String) entry.getValue();
				String newValue = (String) newTitle.get(locale);
				String mergedValue = MergeUtil.mergeHtml(oldValue, newValue);
				mergedTitle.put(locale, mergedValue);
			}
			session.setAttribute(QuestionnaireModuleWebConstants.QUESTION_MERGED_TITLE_KEY, mergedTitle);

            // check 'check all' ckeckbox if needed
            questionForm.setAllCheckedFlagForTitleCheckboxes(request, localesMode);

			return mapping.findForward("callUpdateQuestion");
		}

		if ( session.getAttribute(WebappConstants.REDIRECT_URL_KEY) != null ) {
			String redirectUrl = (String) request.getSession().getAttribute(WebappConstants.REDIRECT_URL_KEY);
			ActionForward redirect = new ActionForward(redirectUrl, true);
			return redirect;
		}

		return mapping.findForward("listQuestions");
	}
}
